<template>
    <div class="flex flex-col h-full p-6 rounded-lg bg-body">
        <div class="flex items-center mb-4">
            <div class="flex items-center flex-1">
                <h2 class="text-2xl ">对话日志</h2>
                <el-button
                    v-if="robot.power >= permissionEnum.ADMIN"
                    class="ml-4"
                    :disabled="selectData.length <= 0"
                    @click="handleDelete(selectData)"
                >批量删除</el-button>
            </div>
            <div class="flex items-center">
                <el-select
                    v-model="queryParams.scene"
                    class="!w-[100px] mr-3"
                    placeholder="请选择"
                >
                    <el-option value="" label="全部"/>
                    <el-option value="normal" label="应用"/>
                    <el-option value="test" label="调试"/>
                    <el-option value="web" label="网页"/>
                    <el-option value="api" label="接口"/>
                </el-select>

                <date-picker
                    v-model:startTime="queryParams.start_time"
                    v-model:endTime="queryParams.end_time"
                />

                <div class="ml-3">
                    <el-button type="primary" @click="resetPaging">查询</el-button>
                    <el-button @click="resetParams">重置</el-button>
                </div>
            </div>
        </div>
        <div class="flex-1 min-h-0">
            <el-table
                v-loading="pager.loading"
                :data="pager.lists"
                size="large"
                style="height: 100%"
                @selection-change="handleSelect"
            >
                <el-table-column type="selection" width="55" />
                <el-table-column label="用户" prop="user" min-width="180">
                    <template #default="scope: { row: RobotJournalRecordsResponse }">
                        <div class="flex items-center">
                            <el-avatar :src="scope.row.user.avatar" style="flex-shrink: 0;" />
                            <div class="grid ml-2">
                                <p class="line-clamp-1">{{ scope.row.user.nickname }}</p>
                                <el-popover
                                    :content="scope.row.user.sn"
                                    effect="dark"
                                    placement="top-start"
                                >
                                    <template #reference>
                                        <p class="text-xs text-tx-placeholder line-clamp-1">
                                            {{ scope.row.user.sn }}
                                        </p>
                                    </template>
                                </el-popover>
                            </div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="提问" prop="question" min-width="200">
                    <template #default="scope: { row: RobotJournalRecordsResponse, $index: number }">
                        <p
                            class="line-clamp-2 cursor-pointer"
                            @click="handlePopup('ask', scope.$index)"
                        >
                            {{ scope.row.question }}
                        </p>
                    </template>
                </el-table-column>
                <el-table-column label="答复" prop="answer" min-width="280">
                    <template #default="scope: { row: RobotJournalRecordsResponse, $index: number }">
                        <p class="line-clamp-2" @click="handlePopup('ask', scope.$index)">
                            {{ scope.row.answer }}
                        </p>
                    </template>
                </el-table-column>
                <el-table-column label="来源" prop="scene" width="80">
                    <template #default="scope: { row: RobotJournalRecordsResponse }">
                        <el-tag v-if="scope.row.scene === 'normal'" type="info">应用</el-tag>
                        <el-tag v-if="scope.row.scene === 'test'" type="info">调试</el-tag>
                        <el-tag v-if="scope.row.scene === 'web'" type="info">网页</el-tag>
                        <el-tag v-if="scope.row.scene === 'api'" type="info">接口</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="引用" prop="quotes" width="90">
                    <template #default="scope: { row: RobotJournalRecordsResponse, $index: number }">
                        <el-tag
                            type="info"
                            class="cursor-pointer"
                            @click="handlePopup('quotes', scope.$index)"
                        >
                            {{ scope.row.quotes.length }}条
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="上下文" prop="context" width="90">
                    <template #default="scope: { row: RobotJournalRecordsResponse, $index: number }">
                        <el-tag
                            type="info"
                            class="cursor-pointer"
                            @click="handlePopup('context', scope.$index)"
                        >
                            {{ scope.row.context.length }}条
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="消耗积分" prop="use_points" min-width="90" />
                <el-table-column label="执行耗时" prop="task_time" min-width="90" />
                <el-table-column label="提问时间" prop="create_time" min-width="120" />
                <el-table-column
                    v-if="robot.power >= permissionEnum.ADMIN"
                    label="操作"
                    width="60"
                    fixed="right"
                >
                    <template #default="scope: { row: RobotJournalRecordsResponse, $index: number }">
                        <el-dropdown>
                            <icon name="el-icon-MoreFilled" color="#999" />
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <el-dropdown-item >
                                        <div
                                            class="flex items-center py-[2px]"
                                            @click="handlePopup('correct', scope.$index)"
                                        >
                                            <icon name="el-icon-Edit"/>
                                            <span class="ml-1">修正</span>
                                        </div>
                                    </el-dropdown-item>
                                    <el-dropdown-item divided>
                                        <div
                                            class="flex items-center py-[2px]"
                                            @click="handleDelete([scope.row.id])"
                                        >
                                            <icon name="el-icon-Delete" />
                                            <span class="ml-1">删除</span>
                                        </div>
                                    </el-dropdown-item>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <div class="flex justify-end my-4 mb-0">
            <paging
                v-model="pager"
                layout="total, sizes, prev, pager, next, jumper"
                @change="queryLists"
            />
        </div>

        <popup-know-correct
            v-if="popupType === 'correct'"
            :show="true"
            :bot="robot.code"
            :question="popupData?.question"
            :answer="popupData?.answer"
            @close="popupType = ''"
        />

        <chatting-popup-context
            :show="popupType === 'context'"
            :context="popupData.context"
            @close="popupType = ''"
        />

        <chatting-popup-quotes
            :show="popupType === 'quotes'"
            :quotes="popupData.quotes"
            @close="popupType = ''"
        />

        <ClientOnly>
            <popup
                width="600px"
                title="对话信息"
                confirmButtonText=""
                cancelButtonText=""
                :show="popupType === 'ask'"
                :async-close="true"
                @close="popupType = ''"
                @confirm="popupType = ''"
            >
                <div class="py-4 px-6">
                    <div class="pb-3">记录时间：{{ popupData?.create_time || '-' }}</div>
                    <div class="pb-3">来源的IP：{{ popupData?.ip || '-' }}</div>
                    <div class="pb-3">消耗积分：{{ popupData.use_points || '-' }}</div>
                    <div class="pb-6">消耗Tokens：{{ popupData.use_tokens || '-' }}</div>

                    <div class="mb-1 text-lg font-bold">提问问题</div>
                    <div class="p-3 mb-4 bg-page">
                        {{ popupData?.question || '-' }}
                        <div class="mt-1">
                            <div class="flex gap-3">
                                <template v-for="(item, index) in popupData.annex" :key="index">
                                    <div
                                        v-if="item.file_type === 'image'"
                                        class="flex items-center justify-center my-1
                                            w-[60px] h-[60px] rounded-md border"
                                    >
                                        <el-image
                                            class="max-w-full max-h-full"
                                            :src="item.file_path"
                                            :preview-src-list="[item.file_path]"
                                        />
                                    </div>
                                </template>
                            </div>

                            <template v-for="(item, index) in popupData.annex" :key="index">
                                <nuxt-link
                                    v-if="item.file_type === 'file'"
                                    :to="item.file_path"
                                    :external="true"
                                    class="flex items-center py-1"
                                >
                                    <el-image
                                        class="w-[16px] h-[16px] mr-1.5"
                                        :src="suffixUtil.findUnitIcon(item.file_name)"
                                    />
                                    <span class="underline hover:text-tx-primary">
                                        {{ item.file_name }}
                                    </span>
                                </nuxt-link>
                            </template>
                        </div>
                    </div>

                    <div class="mb-1 text-lg font-bold">思考过程：</div>
                    <div class="p-3 mb-4 bg-page">
                        {{ popupData?.thinks || '-' }}
                    </div>

                    <div class="mb-1 text-lg font-bold">回复内容：</div>
                    <div class="p-3 bg-page">
                        {{ popupData?.answer }}
                    </div>
                </div>
            </popup>
        </ClientOnly>
    </div>
</template>

<script setup lang="ts">
import { permissionEnum } from '~/enums/app'
import suffixUtil from '~/utils/suffix'
import robotJournalApi from '~/api/agent/robot/journal'
import PopupKnowCorrect from '../../_components/popup-know-correct.vue'

const props = withDefaults(
    defineProps<{
        robot: RobotSmarterDetailResponse
    }>(),
    {}
)

// 编辑数据
const popupType = ref<string>('')
const popupData = ref<RobotJournalRecordsResponse>({} as RobotJournalRecordsResponse)

// 查询参数
const queryParams = reactive({
    bot: props.robot.code,
    scene: '',
    start_time: '',
    end_time: ''
})

// 分页查询
const { pager, queryLists, resetPaging, resetParams } = usePaging({
    fetchFun: robotJournalApi.records,
    params: queryParams
})

/**
 * 处理弹窗
 *
 * @param {string} type
 * @param {number} index
 * @author zero
 */
const handlePopup = (type: string, index: number) => {
    popupType.value = type
    popupData.value = pager.lists[index]
}

/**
 * 勾选数据
 *
 * @param {any[]} val
 * @author zero
 */
const selectData = ref<number[]>([])
const handleSelect = (val: any[]) => {
    selectData.value = val.map((item) => item.id)
}

/**
 * 删除数据
 *
 * @param {number[]} ids
 * @author zero
 */
const handleDelete = async (ids: number[]) => {
    feedback.confirm('您确定要删除？').then(async () => {
        await robotJournalApi.delete({
            bot: props.robot.code,
            ids
        })
        feedback.msgSuccess('删除成功')
        await queryLists()
    }).catch(() => {})
}

onMounted(async () => {
    await queryLists()
})
</script>
